﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ELMApplication.Web
{
    public partial class AttDownload : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["MailGuid"] != null)
            {
                Guid mailGuid = new Guid(Request.QueryString["MailGuid"].ToString());
                download(mailGuid);
            }
        }
        void download(Guid mailGUID)
        {

            
            byte[] data = null;
            string name = "";

            //TODO:获取二进制
            ELMEntities elm = new ELMEntities();
            var list = from q in elm.Attachment
                       where q.MailGuid == mailGUID
                       select q;
            if (list.Count() == 1)
            {
                data = list.First().FileData;
                name = list.First().FileName;
            }
            if (data != null)
            {
                Response.Buffer = true;
                //清除缓冲区中的所有内容
                Response.Clear();
                //设置输出流的类型
                Response.ContentType = "application/octet-stream";
                //为输出流添加HTTP头信息,在这里用图片的名称作为下载的文件名称
                Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(name, System.Text.Encoding.GetEncoding("UTF-8")) + ";");

                byte[] file = data;
                //把二进制字符串写入HTTP输出流
                Response.BinaryWrite(file);
                //向客户端发送所有缓冲的内容
                Response.Flush();
                /**/
                ////将当前所有缓冲的输出发送到客户端,并停止该页的执行
                Response.End();
            }


        }
    }
}
